<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :on-change="handleChange"
      :auto-upload="false"
      style="width: 200px; margin-bottom: 10px"
    >
      <el-button type="primary">导入生管数据表格</el-button>
    </el-upload>
    <el-upload
      class="upload-demo"
      action=""
      :on-change="erpHandleChange"
      :auto-upload="false"
      style="width: 200px; margin-bottom: 10px"
    >
      <el-button type="primary">导入ERP入库数据表格</el-button>
    </el-upload>
    <el-button type="primary" @click="exportNewData">导出合并数据</el-button>
    <el-button type="primary" @click="exportErpB">导出erp多补数据</el-button>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import * as XLSX from "xlsx";

//生管数据
let fileTemp = ref(null);
let orginData = ref([]);
let indexList = [1, 2, 8, 9, 23, 26, 34];

//数据分页
// let currentPage = ref(1);
// let pageSize = ref(10);
// let tableData = computed(() => {
//   const startIndex = (currentPage.value - 1) * pageSize.value;
//   const endIndex = startIndex + pageSize.value;
//   return orginData.value.slice(startIndex, endIndex);
// });

// const handlePageChange = (newPage: number) => {
//   currentPage.value = newPage;
// };
// const handleSizeChange = (val: number) => {
//   pageSize.value=val
// }
/**
 * 改变文件
 */
const handleChange = (file: any, fileList: any) => {
  fileTemp.value = file.raw;
  if (fileTemp.value) {
    if (
      fileTemp.value.type ==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      fileTemp.value.type == "application/vnd.ms-excel"
    ) {
      importfxx(fileTemp.value);
    } else {
      ElMessage.warning({
        type: "warning",
        message: "附件格式错误，请删除后重新上传！",
      });
    }
  } else {
    ElMessage.warning({
      type: "warning",
      message: "请上传附件！",
    });
  }
};

/**
 * 导入文件
 */
const importfxx = (val: any) => {
  console.log("---------------");
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    console.log(jsonData);
    orginData.value = getDataByIndexArray(jsonData, indexList);
    console.log(orginData.value);
  };
  reader.readAsArrayBuffer(val);
};

/**
 * 整理的数据
 * @param data
 * @param indexArray
 */
function getDataByIndexArray(data, indexArray) {
  const result = [];

  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const rowData = {};

    for (let j = 0; j < indexArray.length; j++) {
      const index = indexArray[j];
      rowData[data[0][index]] = row[index];
    }

    result.push(rowData);
  }

  return result;
}

//ERP数据

let erpFileTemp = ref(null);
let erpOrginData = ref([]);
let erpIndexList = [1, 2, 5,11,12 ,14, 19];

/**
 * 改变文件
 */
const erpHandleChange = (file: any, fileList: any) => {
  erpFileTemp.value = file.raw;
  if (erpFileTemp.value) {
    if (
      erpFileTemp.value.type ==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      erpFileTemp.value.type == "application/vnd.ms-excel"
    ) {
      erpImportfxx(erpFileTemp.value);
    } else {
      ElMessage.warning({
        type: "warning",
        message: "附件格式错误，请删除后重新上传！",
      });
    }
  } else {
    ElMessage.warning({
      type: "warning",
      message: "请上传附件！",
    });
  }
};

/**
 * 导入文件
 */
const erpImportfxx = (val: any) => {
  console.log("---------------11111");
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    console.log(jsonData);
    erpOrginData.value = getErpDataByIndexArray(jsonData, erpIndexList);
    console.log('erp数据',erpOrginData.value);
  };
  reader.readAsArrayBuffer(val);
};

/**
 * 整理的数据
 * @param data
 * @param indexArray
 */
function getErpDataByIndexArray(data, indexArray) {
  const result = [];

  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const rowData = {};

    for (let j = 0; j < indexArray.length; j++) {
      const index = indexArray[j];
      rowData[data[0][index]] = row[index];
    }

    result.push(rowData);
  }

  return result;
}
//合并数据
//合并生管数据
const hbsg = () => {
  const mergedData = {};
  orginData.value.forEach((item) => {
    item.订单号 = item.订单号.trim();
    item.生产片数 = Number(item.生产片数);
    item.生产面积 = Number(item.生产面积);
  });
  orginData.value.forEach((item) => {
    if (mergedData[item.订单号]) {
      mergedData[item.订单号].生产片数 += item.生产片数;
      mergedData[item.订单号].生产面积 += item.生产面积;
    } else {
      mergedData[item.订单号] = item;
    }
  });
  const newData = Object.values(mergedData);
  orginData.value = newData;
};
//合并erp
const hberp = () => {
  const mergedData = {};
  erpOrginData.value.forEach((item) => {
    item.订单编号 = item.订单编号.trim();
    item.入库数 = Number(item.入库数);
    item.总面积 = Number(item.总面积);
    item.单价 = Number(item.单价);
    item.纸质 = item.客方纸质.trim();
  });
  erpOrginData.value.forEach((item) => {
    if (mergedData[item.订单编号]) {
      mergedData[item.订单编号].入库数 += item.入库数;
      mergedData[item.订单编号].总面积 += item.总面积;
    } else {
      mergedData[item.订单编号] = item;
    }
  });
  const newData = Object.values(mergedData);
  erpOrginData.value = newData;

};
//导出数据
const exportNewData = () => {
  hbsg();
  hberp();
  orginData.value.forEach((item) => {
    item.订单号 = item.订单号.trim();
    erpOrginData.value.forEach((erpItem) => {
      if (item.订单号.trim() == erpItem.订单编号.trim()) {
        item.erpruku = erpItem.入库数;
        item.erprkmj = erpItem.总面积;
        item.erpdmj = erpItem.单面积;
        item.单价 = erpItem.单价;
        item.纸质 = erpItem.客方纸质
      }
    });
  });

  let tableData = [
    [
      "订单号",
      "客户",
      "长",
      "宽",
      "生产面积",
      "废品面积",
      "生产片数",
      "erp入库总面积",
      "erp单面积",
      "erp入库数",
      "单价",
    ], //导出表头
  ]; // 表格表头
  orginData.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      item.订单号,
      item.客户,
      item.切长,
      item.剖宽,
      item.生产面积,
      item.废品面积,
      item.生产片数,
      item.erprkmj,
      item.erpdmj,
      item.erpruku,
      item.单价
    ];
    console.log(rowData);
    tableData.push(rowData);
  });
  const newArray = erpOrginData.value.filter(
    (item2) => !orginData.value.some((item1) => item1.订单号 === item2.订单编号)
  );
  erpTable.value = newArray
  
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "对比数据"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "生管erp对比数据" + getCurrentTime() + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
//导出多补的数据
let erpTable = ref([]);
const exportErpB = () => {
  let tableData = [
    ["订单编号","客户|名称","入库数", "单面积", "总面积","纸质" ], //导出表头
  ]; // 表格表头
  
  erpTable.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      item.订单编号,
      item['客户|名称'],
      item.入库数,
      item.单面积,
      item.总面积,
      item.纸质
    ];
    console.log(rowData);
    tableData.push(rowData);
  });
  console.log('erp......',tableData);
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "对比数据"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "erp多出来的数据" + getCurrentTime() + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
//获取当前时间
function getCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
    const date = String(now.getDate()).padStart(2, '0'); // 日期补零
    const hour = String(now.getHours()).padStart(2, '0'); // 小时补零
    const minute = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
    const second = String(now.getSeconds()).padStart(2, '0'); // 秒数补零

    return `${year}-${month}-${date} ${hour}-${minute}-${second}`;
}
</script>

<style lang="scss" scoped></style>
